package com.learn.base;

import cn.hutool.crypto.symmetric.PBKDF2;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * PBKDF2工具类
 *
 * @author zhouhaofeng
 * @version 2022/10/21 0021
 * @see [相关类/方法]
 * @since [cloud-phone-baseline]
 */
public class PBKDF2Util
{
	private PBKDF2Util ()
	{

	}

	/**
	 * 算法名称
	 */
	private static final String ALGORITHM = "PBKDF2WithHmacSHA256";

	/**
	 * 生成密文的长度
	 */
	private static final Integer KEY_LENGTH = 512;

	/**
	 * 迭代次数
	 */
	private static final Integer ITERATION_COUNT = 10000;

	/**
	 * 盐的长度
	 */
	public static final Integer SALT_BYTE_SIZE = 32 / 2;

	/**
	 * PBKDF2加密
	 *
	 * @param password 待加密的密码
	 * @param salt     盐
	 * @return 加密后的密文
	 */
	public static String encrypt (String password, byte[] salt)
	{
		PBKDF2 pbkdf2 = new PBKDF2 (ALGORITHM, KEY_LENGTH, ITERATION_COUNT);
		return pbkdf2.encryptHex (password.toCharArray (), salt);
	}

	/**
	 * 构造随机数盐值
	 *
	 * @return 盐值
	 * @throws NoSuchAlgorithmException 算法不存在异常
	 */
	public static byte[] generateSalt () throws NoSuchAlgorithmException
	{
		SecureRandom random = SecureRandom.getInstance ("SHA1PRNG");
		byte[] salt = new byte[SALT_BYTE_SIZE];
		random.nextBytes (salt);
		return salt;
	}
}
